import dayjs from 'dayjs'

export function getThemeColor () {
  return localStorage.getItem('theme-color')
}

export function setThemeColor (color) {
  localStorage.setItem('theme-color', color)
}

export function getToken () {
  return localStorage.getItem('token')
}

export function setToken (token) {
  localStorage.setItem('token', token)
}

export function removeToken () {
  localStorage.removeItem('token')
}

export function getLayoutTabsStatus () {
  return localStorage.getItem('layout-tabs-status')
}

export function setLayoutTabsStatus (status) {
  localStorage.setItem('layout-tabs-status', status)
}

export function clearStorage () {
  localStorage.clear()
}

export function getUserInfoFromStorage () {
  const userInfo = localStorage.getItem('userInfo')
  return JSON.parse(userInfo)
}

export function setUserInfoToStorage (userInfo) {
  userInfo = JSON.stringify(userInfo)
  localStorage.setItem('userInfo', userInfo)
}

export function isExternal (path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

// export const ORIGINAL_THEME_COLOR = '#00CED1' // default color
// export const ORIGINAL_THEME_COLOR = '#009e5b' // default color
export const ORIGINAL_THEME_COLOR = '#2784f4' // default color
export const ORIGINAL_THEME = ORIGINAL_THEME_COLOR

setLayoutTabsStatus(1)

export function confirmDel (vm) {
  return vm.$confirm('您确定要删除该条数据吗？', '温馨提示')
}

export function validateSelection (vm) {
  return new Promise((resolve, reject) => {
    const selection = vm.selection
    if (selection.length > 0) {
      resolve(selection)
    } else {
      vm.$message.error('请至少选择一项进行操作')
      reject(new Error('请至少选择一项进行操作'))
    }
  })
}

export const EXPIRE_TIME_STAMP_KEY = 'expire_time_stamp'
export function hasExpired () {
  const expireTimeStamp = localStorage.getItem(EXPIRE_TIME_STAMP_KEY)
  if (!expireTimeStamp) return true
  // 1小时没有更新expireTimeStamp后认为超时
  return Date.now() - 60 * 60 * 1000 > Number(expireTimeStamp)
}

export function setExpire (timestamp) {
  localStorage.setItem(EXPIRE_TIME_STAMP_KEY, timestamp)
}

export function uuid () {
  return (
    new Date().getTime().toString(16) + Math.random().toString(16).substring(2)
  ).substring(2, 18);
}

export function createMonthRangeOfYear () {
  const end = dayjs().format('YYYY-MM')
  const length = 12
  return Array(length - 1).fill(1).reduce((acc, v, i) => {
    acc.unshift(dayjs().subtract(i + 1, 'month').format('YYYY-MM'))
    return acc
  }, [end])
}
